package com.tzjz.config;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.tzjz.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;

@Component
@RefreshScope
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
    @Value("${gateway.filter.token}")
    private String filterToken;
    @Value("${gateway.filter.loginUrl}")
    private String loginUrl;
    Logger logger = LoggerFactory.getLogger(AuthFilter.class);
    //匹配路径的工具类
    private AntPathMatcher antPathMatcher =new AntPathMatcher();

//    @Resource
//    RestTemplate restTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getHeaders().getFirst(filterToken);
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        URI url = request.getURI();
        String urls = url.getPath();//获得url

        logger.info("=======AuthFilter:token======" + token);
        //跳过token检查接口
        if(ObjectUtil.isNotEmpty(loginUrl)) {
            for (String path : loginUrl.split(",")) {
                if (antPathMatcher.match("/**/"+path+"/**", urls)) {
                    return chain.filter(exchange);
                }
            }
        }
        if (StringUtils.isEmpty(token)) {
            //返回一个错误码 前端去做跳转淘宝授权登录页面 （前端处理）
//           exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
//           return exchange.getResponse().setComplete();
            return generateJSON(exchange,"token为空");
        }
        try{
            JWTUtils.verify(token);//验证令牌
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            return generateJSON(exchange, "无效签名");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            return generateJSON(exchange, "无token过期效签名");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            return generateJSON(exchange, "token算法不一致");
        } catch (Exception e) {
            e.printStackTrace();
            return generateJSON(exchange, "token失效");
        }
        return chain.filter(exchange);
    }


    private <T>Mono generateJSON(ServerWebExchange exchange, T t){
        ServerHttpResponse response = exchange.getResponse();
        byte[] bits = JSON.toJSONString(t).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return -900;
    }

}

